package cn.mickey.exchange.api;

import cn.mickey.exchange.annotation.LoginUser;
import cn.mickey.exchange.annotation.RedisCache;
import cn.mickey.exchange.domain.JsonResponse;
import cn.mickey.exchange.domain.model.UserModel;
import cn.mickey.exchange.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Map;

@RedisCache
@Slf4j
@RestController
@RequestMapping("/user")
public class UserApi {

    @Resource
    private UserService userService;

    @PostMapping("/login")
    public JsonResponse userLogin(@RequestBody UserModel user, HttpSession session) {
        return userService.userLogin(user, session);
    }

    @PostMapping("/sign-in")
    public JsonResponse userSignIn(@RequestBody UserModel user) {
        return userService.userSignIn(user);
    }

    @PostMapping("/check-nickname")
    public JsonResponse checkNicknameAndAccount(@RequestBody UserModel user) {
        return userService.checkNicknameAndAccount(user);
    }

    @PostMapping("/info")
    public JsonResponse getOneUser(Long userId) {
        return userService.getUserById(userId);
    }

    @PostMapping("/update-info")
    public JsonResponse updateUserPublicInfo(@RequestBody UserModel userModel) {
        if (userService.checkNickname(userModel)){
            return JsonResponse.fail("此用户名太受欢迎,请更换一个!");
        }
        if (userService.updateUserInfo(userModel)) {
            return JsonResponse.success("修改成功!");
        }
        return JsonResponse.fail("修改失败!");
    }

    @PostMapping("/password")
    public JsonResponse updateUserPassword(@LoginUser UserModel user,
                                           String newPassword,String oldPassword) throws Exception {
        if (newPassword != null && oldPassword != null){
            if (userService.updatePassword(user.getUserId(),newPassword,oldPassword)) {
                return JsonResponse.success("密码修改成功!");
            }
        }
        return JsonResponse.fail("修改失败!");
    }

    @PostMapping("/infos")
    public JsonResponse pageListUserInfos(@RequestParam Map<String, Object> params) {
        //log.info(params.toString());
        return userService.pageListUserInfos(params);
    }

    @RequestMapping("/logout")
    public JsonResponse logout(HttpSession session) {
        session.removeAttribute("login_user");
        return JsonResponse.success("退出成功!");
    }
}
